import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';

class AccountInfoChangeController extends GetxController {
  /// 响应式成员变量
  final _isPhone = false.obs;

  set isPhone(value) => _isPhone.value = value;

  get isPhone => _isPhone.value;

  /// 成员变量
  late String dialCode;
  late final TextEditingController accountController;

  /// 事件
  Future<void> sendVerificationCode() async {
    if (accountController.text.isEmpty) {
      toast(isPhone ? 'Phone empty'.tr : 'Email empty'.tr);
      return;
    }
    if (!isPhone && !duIsEmail(accountController.text)) {
      toast('Bad email format'.tr);
      return;
    }
    Loading.show();
    await Request()
        .post(
      '/userConfig/sendCode',
      {
        'email': accountController.text,
        'mobile': accountController.text,
        'mobileType': dialCode,
        'sendType': 3,
      }..removeWhere((key, value) =>
          (isPhone && key == 'email') || // tab 1 只能输入 mobile
          (!isPhone && (key == 'mobile' || key == 'mobileType'))), // tab 0 只能输入 email
    )
        .then((_) {
      Get.offAndToNamed(Routes.ACCOUNTINFOCHANGECODE,
          arguments: isPhone
              ? {'type': 0, 'mobile': accountController.text, 'mobileType': dialCode}
              : {'type': 1, 'email': accountController.text});
    });
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    isPhone = Get.arguments['type'] == 0;
    dialCode = ConfigStore.to.countryCode;
    accountController = TextEditingController();
  }
}
